<?php
/**
 * Created by PhpStorm.
 * User: qzy008
 * Date: 2018/9/8
 * Time: 11:08
 */

namespace app\api\service;


use app\lib\exception\TokenException;
use think\Cache;
use think\Exception;
use think\Request;

class Token
{
    public static function generateToken()
    {
        $randStr = generateRandStr(32);
        $timestamp = $_SERVER['REQUEST_TIME'];
        $salt = config('secure.TOKEN_SALT');

        return md5($randStr . $timestamp . $salt);
    }

    public static function getCurrentTokenVar($key)
    {
        $token = Request::instance()
            ->header('token');
        $vars = Cache::get($token);
        if (!$vars) {
            throw new TokenException();
        } else {
            if (!is_array($vars)) {
                $vars = json_decode($vars, true);
            }
            if (array_key_exists($key, $vars)) {
                return $vars[$key];
            } else {
                throw new Exception('尝试获取的Token变量并不存在');
            }
        }
    }

    public static function getCurrentTokenAdminID()
    {
        return self::getCurrentTokenVar('adminID');
    }

    public static function clearTokenCache()
    {
        $token = Request::instance()->header('token');
        if (!$token) {
            throw new TokenException();
        }
        $result = Cache::rm($token);
        return $result;
    }

    public static function checkToken()
    {
        $token = Request::instance()->header('token');
        if (!$token) {
            throw new TokenException(['msg' => 'token参数不存在']);
        }
        $cache = Cache::get($token);
        if (empty($cache)) {
            throw new TokenException();
        }
    }
}